import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, message, Input, Select, Form, Space,Radio, } from 'antd';
import router from 'umi/router';
import { min } from 'lodash';

const { Option } = Select;
const mapStateToProps = (state: any) => ({
    account: state.account,
    loading: state.loading.effects['account/postObjWithRes'],
});
class SendCollectionConfigurationModal extends PureComponent<any, any> {

    formRef = React.createRef<FormInstance>();

    constructor(props: any) {
        super(props);
        this.state = {
            configName: '',
            options: [],
            sendId: null,
            vehicleGroupInfo: null,//选中的车型组
            vin: null,
        };
    }
    componentWillMount() {
        const { dispatch } = this.props;
        dispatch({
          type: 'collectionConfiguration/getDataWithRes',
          payload: { url: '/data/collection/vehicle/allList' },
          callback: e => {
            const arr: any = [];
            e.data.map(d=>{
                arr.push({
                    label: d.vehicleGroupName,
                    value: d.id
                })
            })
            this.setState({
                // options:[{label:'车辆组1', value: 1},{label:'车辆组2', value: 2},{label:'车辆组3', value: 3}],
                options: arr
                    
                })
            }
          },
        );
      }
    componentDidMount() {
        this.props.onRef(this);
    }

    setData = (record) => {
        setTimeout(()=>{
            const fillFileds = {
                id: record.id,
                collectName: record.collectName,
            }
            this.setState({
                configName: record.collectName,
                sendId: record.id,
            })
            this.formRef.current?.setFieldsValue(fillFileds);
        },10)
    }
    
    updateData = () =>{
        const { dispatch } = this.props;
        dispatch({
          type: 'collectionConfiguration/getDataWithRes',
          payload: { url: '/data/collection/vehicle/allList' },
          callback: e => {
            const arr: any = [];
            e.data.map(d=>{
                arr.push({
                    label: d.vehicleGroupName,
                    value: d.id
                })
            })
            this.setState({
                options: arr
                    
                })
            }
          },
        );
    }
    sendConfig = () => {
        this.formRef.current?.submit();
    }

    ok = (values: any) => {
        const { dispatch, formValues, pageObj } = this.props;
        const {configName,sendId, vehicleGroupInfo, vin}=this.state;
        const obj = { ...values };
        const params = {};
        if(obj.type == 0){
          if(!vin){
            message.error("请输入VIN！");
            return;
          }else{
            params['vin']=vin;
          }
        }
        if(obj.type == 1){
            if(!vehicleGroupInfo){
              message.error("请选择车辆组！");
              return;
            }else{
                params['vehicleId']=Number(vehicleGroupInfo.value);
                params['vehicleGroupName']=vehicleGroupInfo.label;
            }
          }
        if(values.collectName){
        params['collectName']=values.collectName;
        }else{
        params['collectName']=configName;
        }
        params['id']=sendId;
        dispatch({
            type: 'collectionConfiguration/postObjWithRes',
            payload: {
                url: '/data/collection/config/issued',
                ...params
            },
            callback: (response: any) => {
                if (response.statusCode === '0') {
                    let params = { ...formValues, page: pageObj.current, size: pageObj.pageSize }
                    this.close();
                    message.success('下发成功');
                    dispatch({
                        type: "collectionConfiguration/postFetchPage",
                        payload: {
                            url: '/data/collection/config/list', ...params,

                        }
                    })
                }
            }
        })
    };
    checkFill = (rule, value, callback) => {
        const type =  this.formRef.current?.getFieldValue('type');
        if (!(type == 0 || type == 1)) {
          callback('请至少选择一项执行车辆类型！');
          return;
        }
        callback();
      };
    close = () => {
        this.formRef.current?.resetFields();
        const { closeModal } = this.props;
        this.setState({
            configName: '',
            options: [],
            sendId: null,
            vehicleGroupInfo: null,//选中的车型组
            vin: null,
        })
        closeModal();
    };
    toSet = () =>{
        router.push('/connectPlat/collectionGroup');
    };
    render() {
        const { modalVisible, loading } = this.props;
        const { configName } = this.state;
        const options = (this.state.options || []).map(d => (
            <Option key={d.value}>{d.label}</Option>
          ));
        const footer = (
            <div>
                <Button size="small" onClick={this.close}>取消</Button>
                <Button size="small" loading={loading} onClick={this.sendConfig} type="primary">确认</Button>
            </div>
        );
        return (
            <Modal
                style={{ top: 20 }}
                width={700}
                footer={footer}
                title="下发采集配置"
                visible={modalVisible}
                onCancel={this.close}
            >
                <Form
                    labelCol={{
                        span: 6,
                      }}
                      wrapperCol={{
                        span: 18,
                      }}
                    ref={this.formRef}
                    onFinish={this.ok}
                >
                    <Form.Item
                        style={{ display: 'none' }}
                        label="sid"
                        name="sid"
                    >
                        <Input readOnly={true} />
                    </Form.Item>
                    <Form.Item
                        label="采集配置名称"
                        name="configName"
                    >
                        {configName}
                    </Form.Item>

                    <Form.Item  label="采集车辆" required>
                       <Form.Item name="type" 
                        noStyle 
                        rules={[{ validator: this.checkFill }]}
                        initialValue={0}
                    >
                     <Radio.Group>
                    <Space direction="vertical">
                       <Space>
                       <Radio value={0} >
                        <div style={{width: '45px'}}>
                        单车
                        </div>
                        </Radio>
                        <Input 
                        style={{width: '200px',borderColor: '#e9e7e7 !important'}}
                        placeholder="请输入VIN"
                        // value ={vin} 
                        onChange={(e) =>{
                            e.persist()
                            if(e){
                            this.setState({
                                vin: e.target.value
                            })
                            }else{
                                this.setState({
                                    vin: null
                                })
                            }
                        }}
                        />
                        </Space>
                        <Space>
                        <Radio value={1}>
                        <div style={{width: '45px'}}>
                       车辆组
                       </div>
                       </Radio>
                       <Select
                        placeholder="请选择车型组"
                        style={{width: '200px',borderColor: '#e9e7e7 !important'}}
                        allowClear
                        labelInValue
                        onChange={(e) =>{
                            if(e){
                            this.setState({
                                vehicleGroupInfo: e
                            })
                            }else{
                                this.setState({
                                    vehicleGroupInfo: null
                                })
                            }
                        }}
                     >
                          {options}
                       </Select>
                       <Button type="link" onClick={this.toSet}><u>去新建</u></Button>
                       </Space>
                    </Space>
                  </Radio.Group>  
                 </Form.Item>
                    </Form.Item>
                </Form>
            </Modal>
        );
    }
}
export default connect(mapStateToProps)(SendCollectionConfigurationModal);